<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS 验证码</title>
    <style>
        .captcha {
            font-size: 24px;
            font-weight: bold;
            letter-spacing: 3px;
            user-select: none;
            cursor: pointer;
        }

        .refresh {
            width: 100px;
            height: 40px;
            background-color: white;
            text-align: center;
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <h1>验证码</h1>
    <div class="refresh">
        <span class="captcha" id="captcha" onclick="generateCaptcha()"></span>
    </div>
    <br>
    <input type="text" id="userInput" placeholder="输入验证码">
    <button onclick="validateCaptcha()">验证</button>

</body>

</html>
<script>
    function generateCaptcha() {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let captcha = '';
        // 用于存储带样式的字符串
        let captchaHTML = '';
        for (let i = 0; i < 4; i++) {
            //每个字母随机一个颜色
            let color = `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}`;
            // 随机选择一个字符
            const char = chars.charAt(Math.floor(Math.random() * chars.length));
            captcha += char;
            // 给每个字母添加样式
            captchaHTML += `<span style="color:${color}">${char}</span>`;
        }
        // 使用innerHTML 显示标签并设置样式
        document.getElementById('captcha').innerHTML = captchaHTML;
    }

    function validateCaptcha() {
        const userInput = document.getElementById('userInput').value;
        const captcha = document.getElementById('captcha').textContent;
        const result = document.getElementById('result');
        if (userInput === captcha) {
            alert('验证成功！');
        } else {
            alert('验证失败！');
        }
    }

    // 初始化验证码
    generateCaptcha();
</script>